package app.objectstoragedemo.exception_advice;



import app.objectstoragedemo.Pojo.Exception.BusinessException;
import app.objectstoragedemo.Pojo.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 异常拦截
 * RestControllerAdvice REST 控制器建议
 * ExceptionHandler 异常处理程序
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends Throwable {

    /**
     * 自定义业务异常拦截
     * BusinessException
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Result<?> businessperson(BusinessException e) {
        log.info("业务异常拦截 {}", e.getMessage());
        return new Result<>(e.getStatus(), false, e.getMessage(), null);
    }


//    /***
//     * 缺少数据 数据 不对 异常
//     */
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public ResponseEntity<?> businessperson(MethodArgumentNotValidException e) {
//        log.info("测试{}",this.getClass());
//        String errorMessage = "缺少数据";
//        if (e.getBindingResult() != null) {
//            errorMessage = e.getBindingResult()
//                    .getFieldErrors()
//                    .stream()
//                    .map(error -> error.getField() + ": " + error.getDefaultMessage())
//                    .collect(Collectors.joining("; "));
//            log.info(" 数据异常 {}", errorMessage);
//        }
//        return  ResponseEntity.badRequest().body(Result.missingParameter(errorMessage));
//    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> exceptionHandler(MethodArgumentNotValidException e) {
        log.info("测试 MethodArgumentNotValidException {}",this.getClass());
        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + "!";
        }
        return Result.missingParameter(errorMesssage);
    }

    /**
     * 缺少数据 数据 不对 异常
     * 验证异常处理程序
     * 校验异常
     */
    @ExceptionHandler(value = BindException.class)
    public Result<?> validationExceptionHandler(BindException e) {

        BindingResult bindingResult = e.getBindingResult();
        String errorMesssage = "";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + "!";
        }
        return Result.missingParameter(errorMesssage);
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Result<?> ConstraintViolationExceptionHandler(ConstraintViolationException ex) {
        log.info("测试 ConstraintViolationExceptionHandler {}",this.getClass());

        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return Result.missingParameter(String.join(",",msgList));
    }


    /**
     * 未知的运行时异常拦截
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result<?> notFount(RuntimeException e) {
        log.info("____________________未知的运行时异常拦截____________________");

        log.error("{}", e.getMessage());
        log.error("{}", e.getClass());

        log.info("________________________________________________________");
        return Result.error(e.getMessage());
    }


}
